<template>
  <div class="wrapper">
    <header class="header" v-if="!isManage">
      <img
        src="@/assets/images/goBackImg.png"
        class="back"
        alt="header"
        @click="goBack"
      />
      <div class="title">收藏夹</div>
      <div class="btn-ba">
        <div class="rightText" @click="handleManage">管理</div>
      </div>
    </header>
    <header class="header" v-else>
      <div class="title" @click="onExitManage">退出编辑</div>
      <div class="title">已选择{{ selectList.length }}项</div>
      <div class="rightText" @click="onSelectAll">
        {{ selectList.length === list.length ? '反选' : '全选' }}
      </div>
    </header>
    <div class="listContainer" v-if="list.length" @scroll="onScroll">
      <VolunteerItem
        v-for="item in list"
        :key="item.id"
        :item="item"
        :showCheck="isManage"
      />
      <div v-if="loading" class="loading full-row">加载中...</div>
      <div v-else-if="!hasMore" class="noMore full-row">没有更多了</div>
    </div>
    <div class="noList" v-else>
      <Empty :size="200" />
    </div>
    <div class="operation">
      <div class="add" v-if="!isManage" @click="onAdd">
        <img class="icon" src="@/assets/images/addIconWhite.png" alt="add" />
        <text class="text">新建志愿表</text>
      </div>
      <div class="add" v-else>
        <img
          class="icon"
          src="@/assets/images/removeIconWhite.png"
          alt="copy"
        />
        <div class="text" @click="onDelete">删除</div>
      </div>
    </div>
    <ConfirmDialog
      v-model:show="show"
      title="温馨提示"
      message="确定删除选中的志愿表吗？"
      @confirm="onConfirmDelete"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast } from 'vant';
import { useVolunteerStore } from '@/store/volunteer';
import { onBackPressed } from '@/utils/androidFn.js';
import VolunteerItem from './components/VolunteerItem.vue';
import ConfirmDialog from '@/components/ConfirmDialog.vue';
import Empty from '@/components/Empty.vue';
import { volunteerBatchDelete, volunteerCollectList } from '@/api/volunteer';

const route = useRoute();
const router = useRouter();
const store = useVolunteerStore();

const isManage = ref(false);
const show = ref(false);
const selectList = ref([]);
const list = ref([]);
const pageNo = ref(1);
const pageSize = 10;
const hasMore = ref(true);
const loading = ref(false);

watch(
  () => list.value,
  (newList) => {
    selectList.value = newList.filter((item) => item.checked);
  },
  { deep: true, immediate: true }
);

const goBack = () => {
  if (route.query?.fromType == 'android') {
    onBackPressed(router);
  } else {
    router.back();
  }
};

const handleManage = () => {
  isManage.value = true;
};

const onExitManage = () => {
  isManage.value = false;
};

const volunteerInfo = computed(() => store.volunteerInfo);
const defaultBatchType = computed(() => store.defaultBatchType); //没有用，先改再说
const volunteerListFn = async () => {
  if (loading.value || !hasMore.value) return;
  loading.value = true;
  const params = {
    pageNo: pageNo.value,
    pageSize,
  };
  const res = await volunteerCollectList(params);
  if (res.code == 200) {
    res.data.forEach((item) => {
      item.checked = false;
    });
    if (pageNo.value === 1) {
      list.value = res.data;
    } else {
      list.value = list.value.concat(res.data);
    }
    if (list.value.length >= res.pageparam.sums) {
      hasMore.value = false;
    } else {
      hasMore.value = true;
      pageNo.value += 1;
    }
    if (!list.value.length) {
      isManage.value = false;
    }
  }
  loading.value = false;
};

const onSelectAll = () => {
  if (selectList.value.length === list.value.length) {
    list.value.forEach((item) => {
      item.checked = false;
    });
  } else {
    list.value.forEach((item) => {
      item.checked = true;
    });
  }
};

let scrollTimer = null;
const onScroll = (e) => {
  if (loading.value || !hasMore.value) return;
  if (scrollTimer) clearTimeout(scrollTimer);
  scrollTimer = setTimeout(() => {
    const el = e.target;
    if (el.scrollHeight - el.scrollTop - el.clientHeight < 50) {
      loadMore();
    }
  }, 100);
};

const loadMore = () => {
  if (loading.value || !hasMore.value) return;
  volunteerListFn();
};

onUnmounted(() => {
  if (scrollTimer) clearTimeout(scrollTimer);
});

const resetList = () => {
  pageNo.value = 1;
  hasMore.value = true;
  list.value = [];
};

const onAdd = () => {
  router.push({
    path: '/home',
  });
};

const onDelete = () => {
  if (!selectList.value.length) {
    showToast('请选择要删除的志愿表');
    return;
  }
  show.value = true;
};

const onConfirmDelete = async () => {
  try {
    const params = {
      volunteerIdList: selectList.value.map((item) => item.volunteerId),
    };
    const res = await volunteerBatchDelete(params);
    show.value = false;
    if (res.code == 200) {
      showToast('删除成功');
      resetList();
      volunteerListFn();
    }
  } catch (error) {
    show.value = false;
    console.log(error, 'error-');
  }
};

onMounted(() => {
  volunteerListFn();
});
</script>

<style scoped lang="scss">
.wrapper {
  height: 100vh;
  background: linear-gradient(180deg, #e8f9ff 0%, #f4f6f8 100%);
  background-repeat: no-repeat;
  background-size: cover;
  display: flex;
  flex-direction: column;
  .header {
    padding: 30px 32px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    line-height: 20px;
    font-size: 13px;
    color: #000;
    position: sticky;
    top: 0;
    z-index: 100;
    .back {
      width: 40px;
      height: 40px;
    }
    .title {
      height: 40px;
      font-size: 30px;
      color: #222222;
      line-height: 40px;
    }
    .rightText {
      font-weight: 400;
      font-size: 30px;
      color: #222222;
      line-height: 40px;
    }
  }
  .listContainer {
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    display: grid;
    grid-template-columns: repeat(
      2,
      minmax(0, 1fr)
    ); /* 关键：minmax(0, 1fr) 允许列收缩到0 */
    grid-auto-rows: min-content;
    gap: 16px;
    padding: 12px 32px;
    box-sizing: border-box;
    .loading,
    .noMore {
      font-size: 22px;
      text-align: center;
      padding: 24px 0 120px 0;
      color: #999;
    }
    .full-row {
      grid-column: 1 / -1;
    }
  }
  .noList {
    display: flex;
    align-items: center;
    justify-content: center;
    height: calc(100vh - 220px);
    .empty {
      width: 500px;
      height: 500px;
    }
  }
  .operation {
    border-radius: 6px;
    position: fixed;
    bottom: 14px;
    left: 0;
    right: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    padding-bottom: calc(
      10px + constant(safe-area-inset-bottom)
    ); /* iOS 11.2 以下 */
    padding-bottom: calc(10px + env(safe-area-inset-bottom)); /* iOS 11.2+ */
    .add {
      background: $primary-color;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #ffffff;
      border-radius: 12px;
      padding: 16px 32px;
      font-weight: bold;
      font-size: 30px;
      line-height: 45px;
      color: #ffffff;
      .icon {
        width: 40px;
        height: 40px;
      }
      .text {
        margin-left: 14px;
      }
    }
  }
}
.dialogContent {
  text-align: center;
  font-size: 15px;
  color: #000000;
  line-height: 22px;
  padding: 32px 0;
  border-bottom: 1px solid #ebedf0;
}
</style>
